package org.example.leetcode.interview.binarysearch;

import org.example.util.IO;

import java.util.Arrays;

public class LC0034 {
    public int[] searchRange(int[] nums, int target) {
        int left = lowerBound(nums, target);
        // 查找最左边或者最左边的值都不是target，那代表没有这个数
        if ((left == nums.length) || nums[left] != target) {
            return new int[]{-1, -1};
        }
        int right = lowerBound(nums, target + 1) - 1;

        return new int[]{left, right};
    }

    private int lowerBound(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        while (left < right) {
            int mid = left + ((right - left) / 2);
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        return left;
    }

    public static void main(String[] args) {
        LC0034 solu = new LC0034();
        System.out.println(Arrays.toString(solu.searchRange(IO.intArray("[5,7,7,8,8,10]"), 8)));
        System.out.println(Arrays.toString(solu.searchRange(IO.intArray("[5,7,7,8,8,10]"), 6)));
        System.out.println(Arrays.toString(solu.searchRange(IO.intArray("[]"), 0)));
    }
}
